﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CameraScreenShot : MonoBehaviour
{
    public Camera camera;
    public Canvas canvas;
    public RectTransform target;

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var mousePosition = Input.mousePosition;
            Debug.Log("current mouse position:" + mousePosition);
            Color clickColor = GetColorAtPosition(RTImage(camera),mousePosition);
            clickColor.a = 1;
            Debug.Log("current mouse color:" + ColorUtility.ToHtmlStringRGB(clickColor));
            Texture2D posTx = Instantiate(Texture2D.whiteTexture);
            posTx.Resize(4,4);
            posTx.SetPixels(new []
            {
                clickColor,clickColor,clickColor,clickColor,
                clickColor,clickColor,clickColor,clickColor,
                clickColor,clickColor,clickColor,clickColor,
                clickColor,clickColor,clickColor,clickColor
                
            });
            GameObject go = new GameObject();
            go.transform.SetParent(target.transform);
            go.AddComponent<RawImage>().texture = posTx;
            Vector2 localPos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(target,mousePosition,camera,out localPos);
            go.transform.localScale = Vector3.one;
            go.transform.localPosition = localPos;
        }
    }

    Texture2D RTImage(Camera camera)
    {
        var currentRT = RenderTexture.active;
        RenderTexture.active = camera.targetTexture;

        camera.Render();

        var mTargetTexture = camera.targetTexture;
        Texture2D image = new Texture2D(mTargetTexture.width, mTargetTexture.height);
        image.ReadPixels(new Rect(0, 0, mTargetTexture.width, mTargetTexture.height), 0, 0);
        image.Apply();

        RenderTexture.active = currentRT;
        return image;
    }
    
    
    Color GetColorAtPosition(Texture2D texture2D,Vector2 position)
    {
        return texture2D.GetPixel((int) position.x,(int) position.y);
    }
}